package xyz.fefine;

import javax.swing.*;
import java.lang.reflect.Method;

/**
 * Created by feng_ on 2016/9/16.
 */
public class Natives {

    public Enviorment enviorment(Enviorment enviorment) {

        append(enviorment,"print",Natives.class,"print",Object.class);
        append(enviorment,"currentTime",Natives.class,"currentTime");
        append(enviorment,"read",Natives.class,"read");
        append(enviorment,"length",Natives.class,"length",String.class);
        append(enviorment,"toInt",Natives.class,"toInt",Object.class);
        return enviorment;
    }

    /**
     *
     * @param env 运行环境
     * @param name 环境中的名字
     * @param clas 所在的类
     * @param methodName 方法名
     * @param params 参数序列
     */
    protected void append(Enviorment env,String name,Class<?> clas,String methodName,Class<?>... params) {
        Method m = null;
        try {
            m = clas.getMethod(methodName, params);
        } catch (NoSuchMethodException e) {
        }
        env.put(name,new NativeFunction(m,methodName));
    }


    public static int print(Object obj) {
        System.out.println(obj.toString());
        return 0;
    }

    public static String read() {
        return JOptionPane.showInputDialog(null);
    }

    public int length(String s) {
        return s.length();
    }

    public int toInt(Object o) {
        if (o instanceof String) {
            return Integer.parseInt((String)o);
        }
        if (o instanceof Integer) {
            return ((Integer) o).intValue();
        } else {
            throw new NumberFormatException(o.toString());
        }

    }

    private static long startTime = System.currentTimeMillis();

    /*
     * @return 从程序启动到现在运行了多长时间
     */
    public static int currentTime() {
        return (int) (System.currentTimeMillis() - startTime);
    }

}
